#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
import os
import json
import logging

def send_wxsms_single(phone_num, template_id, template_param_list):
    """
    单条发送微信消息
    :param phone_num: 手机号-微信ID(默认手机号码)
    :param template_id: 消息模板ID
    :param template_param_list: 消息模板所需参数列表，例如:【验证码：{1}，描述：{2}】，则传递参数 [888,666]按顺序去格式化模板
    :return:
    """
    BASE_DIR = (os.path.dirname(os.path.abspath(__file__)))
    proxies = {'http': '172.29.4.199:3128', 'https': '172.29.4.199:3128'}
    logging.basicConfig(level=logging.DEBUG, format='%(asctime)s, %(filename)s, %(levelname)s, %(message)s',
                        datefmt='%a, %d %b %Y %H:%M:%S',
                        # filename = os.path.join('/tmp','weixin.log'),
                        filename=os.path.join(BASE_DIR, 'weixin.log'),

                        filemode='a')
    #企业微信密钥信息
    corpid = 'ww6fff7c55944984ee'
    appsecret = 'dRymWQMKayzCeo81osLDRd9f5OUCSD_dC2rHbmuPwhc'
    agentid = 1000002
    # 获取accesstoken
    token_url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' + corpid + '&corpsecret=' + appsecret
    req = requests.get(token_url, proxies=proxies, timeout=5)
    accesstoken = req.json()['access_token']
    # 发送消息
    msgsend_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + accesstoken
    params = {
        "touser": phone_num,
        "msgtype": "text",
        "agentid": agentid,
        "text": {
            "content": str(template_id) + str(template_param_list)
        },
        "safe": 0
    }

    # print(msgsend_url)
    # print(json.dumps(params))
    req = requests.post(msgsend_url, data=json.dumps(params), proxies=proxies, timeout=5)
    response = {'result': 1000, 'errmsg': "网络异常发送失败"}
    logging.info('sendto---' + phone_num + ';;消息内容是---' + str(template_id) + str(template_param_list))

# send_wxsms_single("15951863097", "验证码是:", '5564')